import uasyncio as asyncio
import usocket as socket
import ubinascii as binascii

async def websocket_handler(reader, writer):
    # 读取并解析请求行
    request_line = await reader.readline()
    headers = {}
    while True:
        header = await reader.readline()
        if header == b'\r\n':
            break
        key, value = header.decode().strip().split(": ", 1)
        headers[key] = value

    # 计算 Sec-WebSocket-Accept 值
    sec_websocket_key = headers['Sec-WebSocket-Key']
    sec_websocket_accept = binascii.b2a_base64(binascii.hashlib.sha1(sec_websocket_key.encode() + b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest()).decode().strip()

    # 构建并发送 WebSocket 握手响应
    response = (
        b'HTTP/1.1 101 Switching Protocols\r\n'
        b'Upgrade: websocket\r\n'
        b'Connection: Upgrade\r\n'
        b'Sec-WebSocket-Accept: ' + sec_websocket_accept.encode() + b'\r\n'
        b'\r\n'
    )
    await writer.awrite(response)

    # 处理 WebSocket 数据帧
    while True:
        data = await reader.read(1024)
        if not data:
            break
        print("接收到:", data)
        await writer.awrite(data)

    await writer.aclose()
    await reader.aclose()
    print("连接关闭")

async def main():
    # 启动 WebSocket 服务器
    server = await asyncio.start_server(websocket_handler, '192.168.4.1', 8765)
    print('服务器已启动在 ws://192.168.4.1:8765')
    while True:
        await asyncio.sleep(3600)

asyncio.run(main())
